package cn.hfatec.shms.web.xc.xcJjb.service;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;


import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.enums.KeyTypeEnum;
import cn.hfatec.shms.exception.KeyGenException;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.utils.KeyGenUtils;
import cn.hfatec.shms.web.xc.xcJjbmx.dao.XcJjbmxDao;
import cn.hfatec.shms.web.xc.xcJjbmx.model.XcJjbmx;
import cn.hfatec.shms.web.xc.xcJjbmx.service.XcJjbmxService;
import cn.hfatec.shms.web.xc.xcWeek.model.XcWeek;
import cn.hfatec.shms.web.xc.xcWeek.model.XcWeekParams;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hfatec.base.BaseDao;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.shms.web.xc.xcJjb.model.XcJjb;
import cn.hfatec.shms.web.xc.xcJjb.dao.XcJjbDao;
import cn.hfatec.shms.web.xc.xcJjb.model.XcJjbParams;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author hfatec
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Service("XcJjbService")
public class XcJjbService {

    public static final String BEAN_ID = "XcJjbService";

    //注入Dao层
    @Resource(name = "XcJjbDao")
    private XcJjbDao xcJjbDao;
    //注入Dao层
    @Resource(name = "XcJjbmxDao")
    private XcJjbmxDao xcJjbmxDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;
    //服务层
    @Resource(name = "XcJjbmxService")
    private XcJjbmxService xcJjbmxService;

    @Transactional
    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     * 查询数据
     *
     * @param xcJjbParams
     * @param page
     */
    @Transactional
    public Table queryXcJjbTable(XcJjbParams xcJjbParams, Page page) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", xcJjbParams);
        return baseDao.queryTableByPage("queryXcJjbs", params, page);
    }

    /**
     * 插入数据
     *
     * @param xcJjb
     */
    @Transactional
    public void saveXcJjb(XcJjb xcJjb, String[] ids, String[] userName, String[] jkxjYj, String[] jkxjJj, String[] tjJj, String[] tjGj) throws KeyGenException {
        XcJjbmx xcJjbmx = new XcJjbmx();
        if (xcJjb.getId() != null) {
            XcJjb result = getXcJjb(xcJjb.getId());
            if (result != null) {
                xcJjbDao.update(xcJjb);
                if (userName != null) {
                    for (int i = 0; i < userName.length; i++) {
                        xcJjbmx.setJjbId(result.getJjId());
                        if (!userName[i].equals(""))
                            xcJjbmx.setUserName(userName[i]);

                        if (jkxjYj.length != 0) {
                            if (!jkxjYj[i].equals(""))
                                xcJjbmx.setJkxjYj(Integer.parseInt(jkxjYj[i]));
                            else
                                xcJjbmx.setJkxjYj(0);
                        } else
                            xcJjbmx.setJkxjYj(0);
                        if (jkxjJj.length != 0) {
                            if (!jkxjJj[i].equals(""))
                                xcJjbmx.setJkxjJj(Integer.parseInt(jkxjJj[i]));
                            else
                                xcJjbmx.setJkxjJj(0);
                        } else
                            xcJjbmx.setJkxjJj(0);
                        if (tjJj.length != 0) {
                            if (!tjJj[i].equals(""))
                                xcJjbmx.setTjJj(Integer.parseInt(tjJj[i]));
                            else
                                xcJjbmx.setTjJj(0);
                        } else
                            xcJjbmx.setTjJj(0);
                        if (tjGj.length != 0) {
                            if (!tjGj[i].equals(""))
                                xcJjbmx.setTjGj(Integer.parseInt(tjGj[i]));
                            else
                                xcJjbmx.setTjGj(0);
                        } else
                            xcJjbmx.setTjGj(0);
                        if (ids[i] != "") {

                            xcJjbmx.setId(Integer.parseInt(ids[i]));
                            xcJjbmxDao.update(xcJjbmx);
                        } else {

                            xcJjbmx.setId(null);
                            xcJjbmxDao.insert(xcJjbmx);
                        }
                    }
                }

            } else {
                xcJjb.setJjId(KeyGenUtils.createKeyByType(KeyTypeEnum.JJ_KEY));
                xcJjbDao.insert(xcJjb);
                if (userName != null) {
                    for (int i = 0; i < userName.length; i++) {
                        xcJjbmx.setJjbId(xcJjb.getJjId());
                        if (!userName[i].equals(""))
                            xcJjbmx.setUserName(userName[i]);
                        if (jkxjYj.length != 0) {
                            if (!jkxjYj[i].equals(""))
                                xcJjbmx.setJkxjYj(Integer.parseInt(jkxjYj[i]));
                            else
                                xcJjbmx.setJkxjYj(0);
                        } else
                            xcJjbmx.setJkxjYj(0);
                        if (jkxjJj.length != 0) {
                            if (!jkxjJj[i].equals(""))
                                xcJjbmx.setJkxjJj(Integer.parseInt(jkxjJj[i]));
                            else
                                xcJjbmx.setJkxjJj(0);
                        } else
                            xcJjbmx.setJkxjJj(0);
                        if (tjJj.length != 0) {
                            if (!tjJj[i].equals(""))
                                xcJjbmx.setTjJj(Integer.parseInt(tjJj[i]));
                            else
                                xcJjbmx.setTjJj(0);
                        } else
                            xcJjbmx.setTjJj(0);
                        if (tjGj.length != 0) {
                            if (!tjGj[i].equals(""))
                                xcJjbmx.setTjGj(Integer.parseInt(tjGj[i]));
                            else
                                xcJjbmx.setTjGj(0);
                        } else
                            xcJjbmx.setTjGj(0);
                        xcJjbmxDao.insert(xcJjbmx);
                    }
                }
            }
        } else {
            xcJjb.setJjId(KeyGenUtils.createKeyByType(KeyTypeEnum.JJ_KEY));
            xcJjbDao.insert(xcJjb);
            if (userName != null) {
                for (int i = 0; i < userName.length; i++) {
                    xcJjbmx.setJjbId(xcJjb.getJjId());
                    if (!userName[i].equals(""))
                        xcJjbmx.setUserName(userName[i]);
                    if (jkxjYj.length != 0) {
                        if (!jkxjYj[i].equals(""))
                            xcJjbmx.setJkxjYj(Integer.parseInt(jkxjYj[i]));
                        else
                            xcJjbmx.setJkxjYj(0);
                    } else
                        xcJjbmx.setJkxjYj(0);
                    if (jkxjJj.length != 0) {
                        if (!jkxjJj[i].equals(""))
                            xcJjbmx.setJkxjJj(Integer.parseInt(jkxjJj[i]));
                        else
                            xcJjbmx.setJkxjJj(0);
                    } else
                        xcJjbmx.setJkxjJj(0);
                    if (tjJj.length != 0) {
                        if (!tjJj[i].equals(""))
                            xcJjbmx.setTjJj(Integer.parseInt(tjJj[i]));
                        else
                            xcJjbmx.setTjJj(0);
                    } else
                        xcJjbmx.setTjJj(0);
                    if (tjGj.length != 0) {
                        if (!tjGj[i].equals(""))
                            xcJjbmx.setTjGj(Integer.parseInt(tjGj[i]));
                        else
                            xcJjbmx.setTjGj(0);
                    } else
                        xcJjbmx.setTjGj(0);
                    xcJjbmxDao.insert(xcJjbmx);
                }
            }
        }
    }

    /**
     * 删除数据
     *
     * @param id
     */
    @Transactional
    public void deleteXcJjb(Integer id) {

        xcJjbDao.delete(id);
    }

    /**
     * 删除数据
     *
     * @param xcJjbList
     */
    @Transactional
    public void deleteXcJjbBatch(List<String> xcJjbList) {
        for (String id : xcJjbList) {
            XcJjb xcJjb = getXcJjb(Integer.valueOf(id));
            List<XcJjbmx> list = xcJjbmxService.getXcJjbmxs(xcJjb.getJjId());

            for (XcJjbmx xcJjbmx : list) {
                xcJjbmxService.deleteXcJjbmx(xcJjbmx.getId());
            }
            deleteXcJjb(Integer.valueOf(id));
        }
    }

    /**
     * 根据ID获取数据
     *
     * @param id
     */
    @Transactional
    public XcJjb getXcJjb(Integer id) {

        return xcJjbDao.getXcJjbById(id);
    }

    /**
     * 根据ID获取数据
     *
     * @param entryDate
     */
    @Transactional
    public XcJjb getJjbBack(String entryDate) {

        return xcJjbDao.getXcJjbBack(entryDate);
    }

    /**
     * 导出
     *
     * @param
     */
    @Transactional
    public String exportExcel(XcJjbParams xcJjbParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            String clientFileName = encodeFilename(request, System.currentTimeMillis() + "");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName + ".xls");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            List dataList = xcJjbDao.queryXcJjbs(xcJjbParams);
            List nameList = new ArrayList();
            nameList.add("录入日期");
            nameList.add("个人报告领取");
            nameList.add("AK报告领取");
            nameList.add("A健康礼品");
            nameList.add("B健康礼品");
            nameList.add("C健康礼品");
            nameList.add("D_健康礼品");
            nameList.add("用户姓名");
            nameList.add("健康宣教讲解");
            nameList.add("健康宣教引荐");
            nameList.add("体检报告讲解");
            nameList.add("体检报告跟进");
            this.exportExcel(nameList, dataList, os);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @return HSSFWorkbook
     */
    public HSSFWorkbook createWorkbook(List fieldName, List fieldData) {
        List<CodeInfo> vipTypeList = CodeInfoCache.getCodeInfo(CodeType.VIP_TYPE);
        List<CodeInfo> overdueTypeList = CodeInfoCache.getCodeInfo(CodeType.OVERDUE_TYPE);

        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("现场精进表");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCellStyle cellstyle = (HSSFCellStyle) wb.createCellStyle();// 设置表头样式
        cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
        cellstyle.setWrapText(true); // 设置为自动换行
        HSSFFont cellFont = (HSSFFont) wb.createFont(); // 创建表头字体样式
        cellFont.setFontHeightInPoints((short) 10); // 设置字体大小
        cellFont.setFontName("宋体"); // 设置字体类型
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        cellstyle.setFont(cellFont); // 为表头样式设置字体样式


        for (int i = 0; i < fieldName.size(); i++) {
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue((String) fieldName.get(i));
            cell.setCellStyle(cellstyle);
        }

        XcJjb xcJjb = null;

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        for (int i = 0; i < fieldData.size(); i++) {
            row = sheet.createRow(i + 1);
            xcJjb = (XcJjb) fieldData.get(i);
            // 第四步，创建单元格，并设置值

            if (xcJjb.getEntryDate() == null) {
                row.createCell((short) 0).setCellValue("");
            } else {
                row.createCell((short) 0).setCellValue(xcJjb.getEntryDate());
            }
            if (xcJjb.getGrBgrq() == null) {
                row.createCell((short) 1).setCellValue("");
            } else {
                row.createCell((short) 1).setCellValue(xcJjb.getGrBgrq());
            }
            if (xcJjb.getAkBgrq() == null) {
                row.createCell((short) 2).setCellValue("");
            } else {
                row.createCell((short) 2).setCellValue(xcJjb.getAkBgrq());
            }
            if (xcJjb.getALp() == null) {
                row.createCell((short) 3).setCellValue("");
            } else {
                row.createCell((short) 3).setCellValue(xcJjb.getALp());
            }
            if (xcJjb.getBLp() == null) {
                row.createCell((short) 4).setCellValue("");
            } else {
                row.createCell((short) 4).setCellValue(xcJjb.getBLp());
            }
            if (xcJjb.getCLp() == null) {
                row.createCell((short) 5).setCellValue("");
            } else {
                row.createCell((short) 5).setCellValue(xcJjb.getCLp());
            }
            if (xcJjb.getDLp() == null) {
                row.createCell((short) 6).setCellValue("");
            } else {
                row.createCell((short) 6).setCellValue(xcJjb.getDLp());
            }
            if (xcJjb.getUserName() == null) {
                row.createCell((short) 7).setCellValue("");
            } else {
                row.createCell((short) 7).setCellValue(xcJjb.getUserName());
            }
            if (xcJjb.getJkxjYj() == null) {
                row.createCell((short) 8).setCellValue("");
            } else {
                row.createCell((short) 8).setCellValue(xcJjb.getJkxjYj());
            }
            if (xcJjb.getJkxjJj() == null) {
                row.createCell((short) 9).setCellValue("");
            } else {
                row.createCell((short) 9).setCellValue(xcJjb.getJkxjJj());
            }
            if (xcJjb.getTjJj() == null) {
                row.createCell((short) 10).setCellValue("");
            } else {
                row.createCell((short) 10).setCellValue(xcJjb.getTjJj());
            }
            if (xcJjb.getTjGj() == null) {
                row.createCell((short) 11).setCellValue("");
            } else {
                row.createCell((short) 11).setCellValue(xcJjb.getTjGj());
            }

        }
        //自适应列宽
        for (int i = 0; i < fieldName.size(); i++) {
            sheet.autoSizeColumn((short) i);
        }


        return wb;
    }


    //将信息写入输出流的方法。
    public void exportExcel(List fieldName, List fieldData, OutputStream os) throws Exception {
        HSSFWorkbook wb = createWorkbook(fieldName, fieldData);
        wb.write(os);
        os.close();
    }

}